package com.sayimo.maker.user.service.impl;

import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.user.dao.MemberActiveInterfaceDao;
import com.sayimo.maker.user.dao.MemberCustomerInterfaceDao;
import com.sayimo.maker.user.service.CustomerInterfaceService;
import com.sayimo.maker.user.service.MemberCustomerInterfaceService;
import com.sayimo.maker.user.service.WalletInterfaceService;
import com.sayimo.maker.user.vo.MemberCustomer;

/**
 * @Project: sayimoWeixinApi
 * @ClassName: MemberCustomerInterfaceImplService
 * @Description: 会员Service
 * @Author: 王瑞清
 * @Date: 日期：2015年9月11日 时间：下午6:52:22
 * @Version 1.0.0
 */
@Service(value = "memberCustomerInterfaceImplService")
public class MemberCustomerInterfaceImplService implements MemberCustomerInterfaceService {

	private static Log logger = LogFactory.getLog(MemberCustomerInterfaceImplService.class);
	@Autowired
	private MemberCustomerInterfaceDao memberCustomerInterfaceDao;

	
	@Resource(name="customerInterfaceImplService")
	private CustomerInterfaceService customerInterfaceService;
	
	@Resource(name="activeInterfaceImplDao")
	private MemberActiveInterfaceDao activeInterfaceDao;
	
	
	@Resource(name="walletInterfaceService")
	private WalletInterfaceService walletInterfaceService;
	

	public MemberCustomerInterfaceDao getMemberCustomerInterfaceDao() {
		return memberCustomerInterfaceDao;
	}

	public void setMemberCustomerInterfaceDao(
			MemberCustomerInterfaceDao memberCustomerInterfaceDao) {
		this.memberCustomerInterfaceDao = memberCustomerInterfaceDao;
	}

	@Override
	public void insertOrUpdateMemberCustomerOpenId(String openId,String parentIdOpenId,String result)
			throws ServiceException {
		try {
			MemberCustomer paramCustomer = new MemberCustomer();
			//解析json字符串,获得微信的用户信息,进行解析
			Map<String, Object> map = JSONUtil.readValueToMap(result);
			
			paramCustomer.setFromSide("weChat");
			paramCustomer.setHeadPhoto(map.get("headimgurl").toString());
			if(map.get("sex").toString().equals("1")){
				paramCustomer.setSex("M");
			}else if(map.get("sex").toString().equals("2")){
				paramCustomer.setSex("W");
			}else{
				paramCustomer.setSex("");
			}
			paramCustomer.setBaseAreaCode(null);
			String nickName = map.get("nickname").toString();
			String reg = "[^(a-zA-Z0-9\\u4e00-\\u9fa5_\\x20)]";
			Pattern pattern = Pattern.compile(reg);
			Matcher matcher = pattern.matcher(nickName);
			while (matcher.find()) {
				nickName = nickName.replace(matcher.group(), "");
			}
			
			paramCustomer.setAlias(nickName);
			
			MemberCustomer memberCustomer = memberCustomerInterfaceDao.queryMemberCustomerByOpenId(openId);
			if(memberCustomer == null){
				paramCustomer.setOpenId(openId);
				paramCustomer.setCreateDate(new Date());
				if(parentIdOpenId != null && !"".equals(parentIdOpenId)){
					paramCustomer.setParentId(queryMemberCustomerParentId(parentIdOpenId));
				}else{
					paramCustomer.setParentId(0);
				}
				paramCustomer.setAccout(createAccount());
				memberCustomerInterfaceDao.insertMemberCustomerOpenId(paramCustomer);				
				logger.info("parenId="+paramCustomer.getParentId());
			}else{
				paramCustomer.setOpenId(openId);
				memberCustomerInterfaceDao.updateUserInfo(paramCustomer);
			}
		} catch (DaoException de) {
			logger.debug(de);
			de.printStackTrace();
		}
	}
	
	@Override
	public Integer queryMemberCustomerParentId(String openId)
			throws ServiceException {
		Integer parentId = 0;
		try {
			parentId = (Integer) memberCustomerInterfaceDao.queryMemberCustomerParentId(openId);
		} catch (DaoException de) {
			logger.debug(de);
		}
		return parentId;
	}

	@Override
	public String createAccount() throws ServiceException {
		try {
			StringBuffer account = new StringBuffer();
			String str = "0123456789";
			for (int i = 0; i < 11; i++) {
				Random random = new Random();
				account.append(random.nextInt(str.length()));
			}
			Integer count = memberCustomerInterfaceDao.queryMemberCustomereByAccout(account.toString());
			if (count > 0) {
				return createAccount();
			}
			return account.toString();
		} catch (DaoException de) {
			logger.debug(de);
		}
		return "";
	}

	@Override
	public Integer queryMemberCustomerByParentId(Integer parentId) throws ServiceException {
		Integer id = 0;
		try{
			Integer pid = (Integer)memberCustomerInterfaceDao.queryMemberCustomerByParentId(parentId);
			if(pid != null){
				id = pid;
			}
		}catch(DaoException de){
			logger.debug(de);
		}
		return id;
	}

}
